/* 

给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。

 

示例 1：
输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[1,2,3,6,9,8,7,4,5]

示例 2：
输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 

提示：
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

*/

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
    if (!matrix.length) return [];

    const res = [];
    let direction = "right";
    let left = 0,
        right = matrix[0].length - 1,
        top = 0,
        bottom = matrix.length - 1;

    while (left <= right && top <= bottom) {
        if (direction === "right") {
            for (let i = left; i <= right; i++) {
                res.push(matrix[top][i]);
            }
            top++;
            direction = "bottom";
        } else if (direction === "bottom") {
            for (let i = top; i <= bottom; i++) {
                res.push(matrix[i][right]);
            }
            right--;
            direction = "left";
        } else if (direction === "left") {
            for (let i = right; i >= left; i--) {
                res.push(matrix[bottom][i]);
            }
            bottom--;
            direction = "top"
        } else {
            for (let i = bottom; i >= top; i--) {
                res.push(matrix[i][left])
            }
            left++;
            direction = "right";
        }
    }

    return res;
};